<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="设备编码" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          placeholder="请输入设备编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
          <el-option
            v-for="dict in dict.type.pos_device_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pos:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pos:device:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pos:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['pos:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备ID" align="center" prop="deviceId" />
      <el-table-column label="设备编码" align="center" prop="deviceCode" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="设备类型" align="center" prop="deviceType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pos_device_type" :value="scope.row.deviceType"/>
        </template>
      </el-table-column>
      <el-table-column label="IP地址" align="center" prop="ipAddress" width="120" />
      <el-table-column label="MAC地址" align="center" prop="macAddress" width="140" />
      <el-table-column label="固件版本" align="center" prop="firmwareVersion" width="100" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="最后心跳" align="center" prop="lastHeartbeatTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastHeartbeatTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pos:device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewHeartbeat(scope.row)"
            v-hasPermi="['pos:device:query']"
          >心跳</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleConfig(scope.row)"
            v-hasPermi="['pos:device:edit']"
          >配置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-cpu"
            @click="handleDebug(scope.row)"
            v-hasPermi="['pos:device:edit']"
          >调试</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handlePermission(scope.row)"
            v-hasPermi="['pos:device:edit']"
          >权限</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pos:device:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编码" prop="deviceCode">
              <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="form.deviceType" placeholder="请选择设备类型">
                <el-option
                  v-for="dict in dict.type.pos_device_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ipAddress">
              <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MAC地址" prop="macAddress">
              <el-input v-model="form.macAddress" placeholder="请输入MAC地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="固件版本" prop="firmwareVersion">
              <el-input v-model="form.firmwareVersion" placeholder="请输入固件版本" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备心跳信息对话框 -->
    <el-dialog title="设备心跳信息" :visible.sync="heartbeatOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备编码">{{ heartbeatInfo.deviceCode }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ heartbeatInfo.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="心跳时间">{{ parseTime(heartbeatInfo.heartbeatTime) }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">{{ heartbeatInfo.deviceStatus }}</el-descriptions-item>
        <el-descriptions-item label="CPU使用率">{{ heartbeatInfo.cpuUsage }}%</el-descriptions-item>
        <el-descriptions-item label="内存使用率">{{ heartbeatInfo.memoryUsage }}%</el-descriptions-item>
        <el-descriptions-item label="磁盘使用率">{{ heartbeatInfo.diskUsage }}%</el-descriptions-item>
        <el-descriptions-item label="网络状态">{{ heartbeatInfo.networkStatus }}</el-descriptions-item>
        <el-descriptions-item label="IP地址" :span="2">{{ heartbeatInfo.ipAddress }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ heartbeatInfo.remark }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="heartbeatOpen = false">关 闭</el-button>
        <el-button type="primary" @click="refreshHeartbeat">刷新</el-button>
      </div>
    </el-dialog>

    <!-- 设备配置对话框 -->
    <el-dialog title="设备配置" :visible.sync="configOpen" width="600px" append-to-body>
      <el-form ref="configForm" :model="configForm" label-width="120px">
        <el-form-item label="打印配置">
          <el-input v-model="configForm.printConfig" type="textarea" :rows="3" placeholder="请输入打印配置" />
        </el-form-item>
        <el-form-item label="网络配置">
          <el-input v-model="configForm.networkConfig" type="textarea" :rows="3" placeholder="请输入网络配置" />
        </el-form-item>
        <el-form-item label="系统配置">
          <el-input v-model="configForm.systemConfig" type="textarea" :rows="3" placeholder="请输入系统配置" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="configOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitConfig">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 设备调试对话框 -->
    <el-dialog title="设备调试" :visible.sync="debugOpen" width="800px" append-to-body>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card header="发送调试指令">
            <el-form ref="debugForm" :model="debugForm" label-width="100px">
              <el-form-item label="指令类型">
                <el-select v-model="debugForm.commandType" placeholder="请选择指令类型">
                  <el-option label="信息查询" value="INFO" />
                  <el-option label="配置查询" value="CONFIG" />
                  <el-option label="状态查询" value="STATUS" />
                  <el-option label="日志查询" value="LOG" />
                  <el-option label="重置设备" value="RESET" />
                  <el-option label="自定义" value="CUSTOM" />
                </el-select>
              </el-form-item>
              <el-form-item label="调试指令">
                <el-input v-model="debugForm.command" type="textarea" :rows="3" placeholder="请输入调试指令" />
              </el-form-item>
              <el-form-item label="指令参数">
                <el-input v-model="debugForm.parameters" placeholder="请输入指令参数（可选）" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="debugForm.remark" placeholder="请输入备注（可选）" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitDebugCommand">发送指令</el-button>
                <el-button @click="loadDebugLogs">刷新日志</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card header="调试日志">
            <div slot="header" class="clearfix">
              <span>调试日志</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="clearDebugLogs">清除日志</el-button>
            </div>
            <div style="height: 300px; overflow-y: auto;">
              <div v-for="(log, index) in debugLogs" :key="index" class="debug-log-item">
                <div class="log-header">
                  <span class="log-time">{{ parseTime(log.createTime, '{h}:{i}:{s}') }}</span>
                  <el-tag :type="getLogLevelType(log.logLevel)" size="mini">{{ log.logLevel }}</el-tag>
                  <span class="log-type">{{ log.logType }}</span>
                </div>
                <div class="log-content">{{ log.logContent }}</div>
              </div>
              <div v-if="debugLogs.length === 0" class="no-logs">暂无调试日志</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="debugOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 设备权限管理对话框 -->
    <DeviceGroupPermission
      :visible.sync="permissionOpen"
      :device-data="currentDevice"
      @refresh="getList"
    />
  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice, updateDeviceStatus, getDeviceHeartbeat, updateDeviceConfig, sendDebugCommand, getDeviceDebugLogs, clearDeviceDebugLogs } from "@/api/pos/device";
import DeviceGroupPermission from "./DeviceGroupPermission.vue";

export default {
  name: "Device",
  dicts: ['sys_normal_disable', 'pos_device_type'],
  components: {
    DeviceGroupPermission
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示心跳信息弹出层
      heartbeatOpen: false,
      // 是否显示配置弹出层
      configOpen: false,
      // 是否显示调试弹出层
      debugOpen: false,
      // 是否显示权限管理弹出层
      permissionOpen: false,
      // 心跳信息
      heartbeatInfo: {},
      // 配置表单
      configForm: {},
      // 调试表单
      debugForm: {
        command: '',
        commandType: 'INFO',
        parameters: '',
        remark: ''
      },
      // 调试日志列表
      debugLogs: [],
      // 当前设备数据
      currentDevice: null,
      // 当前设备ID
      currentDeviceId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceCode: null,
        deviceName: null,
        deviceType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceCode: [
          { required: true, message: "设备编码不能为空", trigger: "blur" }
        ],
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        ipAddress: [
          { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: "请输入正确的IP地址", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        deviceCode: null,
        deviceName: null,
        deviceType: null,
        ipAddress: null,
        macAddress: null,
        firmwareVersion: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      getDevice(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 查看心跳信息 */
    handleViewHeartbeat(row) {
      this.currentDeviceId = row.deviceId;
      getDeviceHeartbeat(row.deviceId).then(response => {
        this.heartbeatInfo = response.data;
        this.heartbeatOpen = true;
      });
    },
    /** 刷新心跳信息 */
    refreshHeartbeat() {
      if (this.currentDeviceId) {
        getDeviceHeartbeat(this.currentDeviceId).then(response => {
          this.heartbeatInfo = response.data;
          this.$modal.msgSuccess("刷新成功");
        });
      }
    },
    /** 设备配置 */
    handleConfig(row) {
      this.currentDeviceId = row.deviceId;
      this.configForm = {
        printConfig: "",
        networkConfig: "",
        systemConfig: ""
      };
      this.configOpen = true;
    },
    /** 提交配置 */
    submitConfig() {
      updateDeviceConfig(this.currentDeviceId, this.configForm).then(response => {
        this.$modal.msgSuccess("配置更新成功");
        this.configOpen = false;
      });
    },
    /** 设备调试 */
    handleDebug(row) {
      this.currentDeviceId = row.deviceId;
      this.debugForm = {
        command: '',
        commandType: 'INFO',
        parameters: '',
        remark: ''
      };
      this.debugOpen = true;
      this.loadDebugLogs();
    },
    /** 加载调试日志 */
    loadDebugLogs() {
      if (this.currentDeviceId) {
        getDeviceDebugLogs(this.currentDeviceId, {}).then(response => {
          this.debugLogs = response.rows || [];
        });
      }
    },
    /** 发送调试指令 */
    submitDebugCommand() {
      if (!this.debugForm.command.trim()) {
        this.$modal.msgError("请输入调试指令");
        return;
      }
      
      const request = {
        deviceId: this.currentDeviceId,
        command: this.debugForm.command,
        commandType: this.debugForm.commandType,
        parameters: this.debugForm.parameters,
        remark: this.debugForm.remark
      };
      
      sendDebugCommand(this.currentDeviceId, request).then(response => {
        this.$modal.msgSuccess("调试指令已发送");
        this.loadDebugLogs();
        this.debugForm.command = '';
        this.debugForm.parameters = '';
        this.debugForm.remark = '';
      });
    },
    /** 清除调试日志 */
    clearDebugLogs() {
      this.$modal.confirm('确认要清除该设备的所有调试日志吗？').then(() => {
        clearDeviceDebugLogs(this.currentDeviceId).then(response => {
          this.$modal.msgSuccess("调试日志已清除");
          this.loadDebugLogs();
        });
      });
    },
    /** 设备权限管理 */
    handlePermission(row) {
      this.currentDevice = row;
      this.currentDeviceId = row.deviceId;
      this.permissionOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除设备编号为"' + deviceIds + '"的数据项？').then(function() {
        return delDevice(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pos/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
